package com.web.servlet;

import com.bean.Goods;
import com.service.GoodsService;
import com.service.impl.GoodsServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Date;
import java.util.UUID;

@WebServlet("/upGood")
@MultipartConfig
public class upGoodServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String gid = request.getParameter("gid");
        String gname = request.getParameter("gname");
        Part gimg = request.getPart("gimg");
        String gprice = request.getParameter("gprice");
        String gstock = request.getParameter("gstock");
        String date = request.getParameter("maintainDate");
        String classify = request.getParameter("classify");
        String gdescribe = request.getParameter("gdescribe");
        //获取文件名
        String fileName = gimg.getSubmittedFileName();
        //获取随机ID
        UUID uuid = UUID.randomUUID();
        //获取当前时间的时间戳
        long time = new Date().getTime();
        //给图片名添加唯一名
        fileName = uuid.toString()+time+fileName;
        //给文件路径添加对应时间、
        LocalDate localDate = LocalDate.now();
        //存放于数据库中的位置
        String path ="img/tou/"+localDate.getYear()
                +"/"+localDate.getMonthValue()+"/"+localDate.getDayOfMonth()+"/"+fileName;
        //创建文件路径用于保存图片
        File file = new File(getServletContext().getRealPath("/"+path));
        //判断父级目录是否存在
        if(!file.getParentFile().exists()){
            file.mkdirs();
        }
        //将文件放入指定位置
        gimg.write(file.toString());


        GoodsService goodsService = new GoodsServiceImpl();
        Goods goods =new Goods(Long.parseLong(gid),gname,"./"+path,Double.parseDouble(gprice),
                Long.parseLong(gstock),date,classify,gdescribe);

        if(goodsService.upGood(goods))
            request.getSession().setAttribute("operateFruit","修改成功");
        else
            request.getSession().setAttribute("operateFruit","修改失败");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(1);
        request.getRequestDispatcher("goods").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }
}
